package com.ezgo.erc.master.utils;

import java.io.UnsupportedEncodingException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;

/**
 * String工具类
 * 
 * @author devintam
 * 
 * @date 2015-07-09
 *
 */
public class StringUtil extends StringUtils {

	/**
	 * 替换掉HTML标签方法
	 */
	public static String replaceHtml(String html) {
		if (isBlank(html)) {
			return "";
		}
		String regEx = "<.+?>";
		Pattern p = Pattern.compile(regEx);
		Matcher m = p.matcher(html);
		String s = m.replaceAll("");
		return s;
	}

	/**
	 * 
	 * TODO( 将xml文档转换为可传输的字符串)
	 *
	 * @param source
	 * @return String
	 */
	public static String xmlToString(String source) {
		String result = source.replaceAll("<", "&lt;");
		result = result.replaceAll(">", "&gt;");
		return result;
	}

	/**
	 * 
	 * TODO(将返回的字符串转换为可反序列化XML文本)
	 *
	 * @param source
	 * @return String
	 */
	public static String stringToXml(String source) {
		String result = source.replaceAll("&lt;", "<");
		result = result.replaceAll("&gt;", ">");
		return result;
	}

	/**
	 * 缩略字符串（不区分中英文字符）
	 * 
	 * @param str
	 *            目标字符串
	 * @param length
	 *            截取长度
	 * @return
	 */
	public static String abbr(String str, int length) {
		if (str == null) {
			return "";
		}
		try {
			StringBuilder sb = new StringBuilder();
			int currentLength = 0;
			for (char c : str.toCharArray()) {
				currentLength += String.valueOf(c).getBytes(
						Constants.DEFAULT_ENCODING).length;
				if (currentLength <= length - 3) {
					sb.append(c);
				} else {
					sb.append("...");
					break;
				}
			}
			return sb.toString();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 功能描述：判断是否为整数
	 * 
	 * @param str
	 *            传入的字符串
	 * @return 是整数返回true,否则返回false
	 */
	public static boolean isInteger(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?[\\d]+$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断是否为浮点数，包括double和float
	 * 
	 * @param str
	 *            传入的字符串
	 * @return 是浮点数返回true,否则返回false
	 */
	public static boolean isDouble(String str) {
		Pattern pattern = Pattern.compile("^[-\\+]?\\d+\\.\\d+$");
		return pattern.matcher(str).matches();
	}

	/**
	 * 判断是不是合法字符 c 要判断的字符
	 */
	public static boolean isLetter(String str) {
		if (str == null || str.length() < 0) {
			return false;
		}
		Pattern pattern = Pattern.compile("[\\w\\.-_]*");
		return pattern.matcher(str).matches();
	}

	/**
	 * 转换为Double类型
	 * 
	 * @param val
	 * @return
	 */
	public static Double toDouble(Object val) {
		if (val == null) {
			return 0D;
		}
		try {
			return Double.valueOf(trim(val.toString()));
		} catch (Exception e) {
			return 0D;
		}
	}

	/**
	 * 转换为Float类型
	 * 
	 * @param val
	 * @return
	 */
	public static Float toFloat(Object val) {
		if (val == null) {
			return 0F;
		}
		try {
			return Float.valueOf(trim(val.toString()));
		} catch (Exception e) {
			return 0F;
		}
	}

	/**
	 * 转换为Long类型
	 * 
	 * @param val
	 * @return
	 */
	public static Long toLong(Object val) {
		if (val == null) {
			return 0L;
		}
		try {
			return Long.valueOf(trim(val.toString()));
		} catch (Exception e) {
			return 0L;
		}
	}

	/**
	 * 转换为Integer类型
	 * 
	 * @param val
	 * @return
	 */
	public static Integer toInteger(Object val) {
		if (val == null) {
			return 0;
		}
		try {
			return Integer.valueOf(trim(val.toString()));
		} catch (Exception e) {
			return 0;
		}
	}

	/**
	 * 判断类是否是json结构
	 * 
	 * @param value
	 *            json字符串
	 * @param cls
	 *            .class
	 * @return
	 */
	public static boolean isJson(String value) {
		boolean flag = false;
		try {
			Object obj = JSON.parse(value);
			if (!"null".equals(value) && !"{}".equals(value) && obj != null)
				flag = true;
		} catch (Exception e) {

		}
		return flag;
	}

	/**
	 * 
	 * TODO(验证URL合法性)
	 *
	 * @param pInput
	 * @return boolean
	 */
	public static boolean isLegalUrl(String pInput) {
		if (pInput == null) {
			return false;
		}
		String regEx = "^(http|https|ftp)//://([a-zA-Z0-9//.//-]+(//:[a-zA-"
				+ "Z0-9//.&%//$//-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{"
				+ "2}|[1-9]{1}[0-9]{1}|[1-9])//.(25[0-5]|2[0-4][0-9]|[0-1]{1}"
				+ "[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)//.(25[0-5]|2[0-4][0-9]|"
				+ "[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)//.(25[0-5]|2[0-"
				+ "4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0"
				+ "-9//-]+//.)*[a-zA-Z0-9//-]+//.[a-zA-Z]{2,4})(//:[0-9]+)?(/"
				+ "[^/][a-zA-Z0-9//.//,//?//'///////+&%//$//=~_//-@]*)*$";
		Pattern p = Pattern.compile(regEx);
		Matcher matcher = p.matcher(pInput);
		return matcher.matches();
	}

	/**
	 * 
	 * TODO(获得用户远程地址)
	 *
	 * @param request
	 * @return String
	 */
	public static String getRemoteAddr(HttpServletRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		} else if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		} else if (isNotBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
	}
}
